package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import control.*;
import model.Employee;

import javax.swing.border.EmptyBorder;

import java.awt.Toolkit;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableColumn;

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

@SuppressWarnings({ "serial", "unused", "deprecation" })
public class employees extends JFrame {

        private JPanel contentPane;
        private JTable empTable;
        private JPanel empPanel;
        private JLabel lblEcpr;
        private JLabel lblEname;
        private JLabel lblEaddress;
        private JLabel lblEzipCode;
        private JLabel lblEcity;
        private JLabel lblEphone;
        private JLabel lblEgsm;
        private JLabel lblEemail;
        private JLabel lblManageEmployees;
        private JScrollPane scrollPane;
        private JLabel lblListOfEmployees;
        private JTextField tfEcpr;
        private JTextField tfEname;
        private JTextField tfEaddress;
        private JTextField tfEzipCode;
        private JTextField tfEcity;
        private JTextField tfEphone;
        private JTextField tfEgsm;
        private JTextField tfEemail;
        private PersonCtrl personCtrl = new PersonCtrl();
        private JButton btnEadd;
        private JButton btnEupdate;
        private JButton btnEdelete;
        private JPasswordField tfEpassword;
        private JPasswordField tfEconfirmPassword;
        private JComboBox<String> comboAccess;
        private JComboBox<String> comboEmp;
        private static employeeTable empT = new employeeTable();
        private static TableColumn cprColumn;
        private static TableColumn accessColumn;
        private static TableColumn passwordColumn;
        private boolean accessType = true;
        private String status = "Enabled";

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
                EventQueue.invokeLater(new Runnable() {
                        public void run() {
                                try {
                                        employees frame = new employees();
                                        frame.setVisible(true);
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                });
        }

        /**
         * Create the frame.
         */
        public employees() 
        {
                setTitle("EMPLOYEES MENU");
                setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Andrada\\Desktop\\images.jpg"));
                setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                setBounds(100, 100, 1050, 600);
                contentPane = new JPanel();
                contentPane.setBackground(new Color(255, 255, 153));
                contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
                setContentPane(contentPane);
                contentPane.setLayout(null);
                
                scrollPane = new JScrollPane();
                scrollPane.setBounds(10, 50, 692, 502);
                contentPane.add(scrollPane);
                
                empTable = new JTable();
                
                empTable.setModel(new javax.swing.table.DefaultTableModel(
                    new Object [][]{},
                    new String []
                    {
                                "Name", "Address", "Zipcode", "City", "Phone", "GSM", "E-mail", "CPR", "Access", "Password"
                    }));
                scrollPane.setViewportView(empTable);
                
                empPanel = new JPanel();
                empPanel.setBackground(new Color(255, 255, 153));
                empPanel.setLayout(null);
                empPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Employee Control", TitledBorder.CENTER, TitledBorder.TOP, null, null));
                empPanel.setBounds(712, 51, 312, 501);
                contentPane.add(empPanel);
                
                lblEcpr = new JLabel("CPR :");
                lblEcpr.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEcpr.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEcpr.setBounds(40, 16, 82, 31);
                empPanel.add(lblEcpr);
                
                tfEcpr = new JTextField();
                tfEcpr.setColumns(10);
                tfEcpr.setBounds(130, 20, 170, 25);
                empPanel.add(tfEcpr);
                
                lblEname = new JLabel("Name :");
                lblEname.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEname.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEname.setBounds(40, 58, 82, 31);
                empPanel.add(lblEname);
                
                lblEaddress = new JLabel("Address :");
                lblEaddress.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEaddress.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEaddress.setBounds(40, 100, 82, 31);
                empPanel.add(lblEaddress);
                
                tfEname = new JTextField();
                tfEname.setColumns(10);
                tfEname.setBounds(130, 62, 170, 25);
                empPanel.add(tfEname);
                
                tfEaddress = new JTextField();
                tfEaddress.setColumns(10);
                tfEaddress.setBounds(130, 104, 170, 25);
                empPanel.add(tfEaddress);
                
                lblEzipCode = new JLabel("Zip Code :");
                lblEzipCode.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEzipCode.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEzipCode.setBounds(40, 142, 82, 31);
                empPanel.add(lblEzipCode);
                
                lblEcity = new JLabel("City :");
                lblEcity.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEcity.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEcity.setBounds(40, 184, 82, 31);
                empPanel.add(lblEcity);
                
                lblEphone = new JLabel("Phone :");
                lblEphone.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEphone.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEphone.setBounds(40, 226, 82, 31);
                empPanel.add(lblEphone);
                
                lblEgsm = new JLabel("GSM :");
                lblEgsm.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEgsm.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEgsm.setBounds(40, 268, 82, 31);
                empPanel.add(lblEgsm);
                
                lblEemail = new JLabel("Email :");
                lblEemail.setHorizontalAlignment(SwingConstants.RIGHT);
                lblEemail.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblEemail.setBounds(40, 310, 82, 31);
                empPanel.add(lblEemail);
                
                tfEzipCode = new JTextField();
                tfEzipCode.setColumns(10);
                tfEzipCode.setBounds(130, 146, 170, 25);
                empPanel.add(tfEzipCode);
                
                tfEcity = new JTextField();
                tfEcity.setColumns(10);
                tfEcity.setBounds(130, 188, 170, 25);
                empPanel.add(tfEcity);
                
                tfEphone = new JTextField();
                tfEphone.setColumns(10);
                tfEphone.setBounds(130, 230, 170, 25);
                empPanel.add(tfEphone);
                
                tfEgsm = new JTextField();
                tfEgsm.setColumns(10);
                tfEgsm.setBounds(130, 272, 170, 25);
                empPanel.add(tfEgsm);
                
                tfEemail = new JTextField();
                tfEemail.setColumns(10);
                tfEemail.setBounds(130, 314, 170, 25);
                empPanel.add(tfEemail);
                
                JLabel lblPassword = new JLabel("Password :");
                lblPassword.setBackground(Color.WHITE);
                lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
                lblPassword.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblPassword.setBounds(10, 386, 112, 31);
                empPanel.add(lblPassword);
                
                comboAccess = new JComboBox<String>();
                comboAccess.setBounds(130, 350, 170, 25);
                empPanel.add(comboAccess);
                
                DefaultComboBoxModel<String> accessModel = new DefaultComboBoxModel<String>();
                accessModel.addElement("Limited Access");
                accessModel.addElement("Full Access");
                comboAccess.setModel(accessModel);
                comboAccess.setSelectedIndex(-1);
                
                JLabel lblConfirmPassword = new JLabel("Confirm Password :");
                lblConfirmPassword.setHorizontalAlignment(SwingConstants.RIGHT);
                lblConfirmPassword.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblConfirmPassword.setBounds(-8, 417, 130, 31);
                empPanel.add(lblConfirmPassword);
                
                empTable.addMouseListener(new MouseAdapter() {
                	  public void mouseClicked(MouseEvent e) {
                	    if (e.getClickCount() == 2 && accessType) {
                	      JTable target = (JTable)e.getSource();
                	      int row = target.getSelectedRow();
                	      setEmployeeFields((String)empTable.getModel().getValueAt(row, 7));
                	    }
                	  }
                	});
                
                btnEadd = new JButton("Add");
                btnEadd.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                        		tfEpassword.setBackground(Color.WHITE);
                        		tfEconfirmPassword.setBackground(Color.WHITE);
                                if(ifEmpty() || ifPasswordEmpty()) return;
                                if(ifEmployeeExists())
                        		{
                        			JOptionPane.showMessageDialog(null,"Employee with this CPR already exists.");
                        			return;
                        		}
                                if(ifPasswordsDontMatch()) return;
                                try 
                                {
                                	if(!ifPersonExists())
                                	{
                                        personCtrl.createPerson(tfEname.getText(), tfEaddress.getText(), tfEzipCode.getText(), tfEcity.getText(),
                                                                 tfEphone.getText(), tfEgsm.getText(), tfEemail.getText(), tfEcpr.getText());
                                        personCtrl.createEmployee(tfEcpr.getText(), tfEpassword.getText(), (String)comboAccess.getSelectedItem(), "Enabled");
                                        updateEmployeeTable();
                                        clearTextFields();
                                        JOptionPane.showMessageDialog(null,"Employee has been successfuly created.");
                                	}
                                	else
                                	{
                                		personCtrl.updatePerson(tfEname.getText(), tfEaddress.getText(), tfEzipCode.getText(), tfEcity.getText(),
                                                tfEphone.getText(), tfEgsm.getText(), tfEemail.getText(), tfEcpr.getText());
                                		personCtrl.createEmployee(tfEcpr.getText(), tfEpassword.getText(), (String)comboAccess.getSelectedItem(), "Enabled");
                                        updateEmployeeTable();
                                        clearTextFields();
                                        JOptionPane.showMessageDialog(null,"Employee has been successfuly created.");
                                	}
                                } 
                                catch (Exception r) 
                                {
                                        JOptionPane.showMessageDialog(null,"Error in creating Employee.");
                                }

                        }
                });
                btnEadd.setBounds(10, 459, 90, 31);
                empPanel.add(btnEadd);
                btnEadd.setFont(new Font("Times New Roman", Font.BOLD, 17));
                
                btnEupdate = new JButton("Update");
                btnEupdate.addActionListener(new ActionListener() {
                	public void actionPerformed(ActionEvent e) {
                			tfEpassword.setBackground(Color.WHITE);
                			tfEconfirmPassword.setBackground(Color.WHITE);
                			if(ifEmpty()) return;
                			if(ifEmployeeExists() == false)
                    		{
                    			JOptionPane.showMessageDialog(null,"Employee with this CPR does not exist.");
                    			return;
                    		}
                			if(ifPasswordsDontMatch()) return;
                			try
                			{
                				personCtrl.updatePerson(tfEname.getText(), tfEaddress.getText(), tfEzipCode.getText(), tfEcity.getText(),
                                                         tfEphone.getText(), tfEgsm.getText(), tfEemail.getText(), tfEcpr.getText());
                				if(tfEpassword.getText().equals(""))
                					personCtrl.updateEmployee(tfEcpr.getText(), personCtrl.getEmployeeByCpr(tfEcpr.getText()).getPassword(), (String)comboAccess.getSelectedItem(), "Enabled");
                				else
                					personCtrl.updateEmployee(tfEcpr.getText(), tfEpassword.getText(), (String)comboAccess.getSelectedItem(), "Enabled");
                				updateEmployeeTable();
                				clearTextFields();
                                JOptionPane.showMessageDialog(null,"Employee has been successfuly updated.");
                			}
                			catch(Exception r)
                			{
                				JOptionPane.showMessageDialog(null,"Error in updating Employee.");
                			}
                	}
                });
                btnEupdate.setBounds(110, 459, 90, 31);
                empPanel.add(btnEupdate);
                btnEupdate.setFont(new Font("Times New Roman", Font.BOLD, 17));
                
              
                
                btnEdelete = new JButton("Delete");
                btnEdelete.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                        		if(ifEmployeeExists() == false)
                        		{
                        			JOptionPane.showMessageDialog(null,"Employee with this CPR does not exist. Enter a valid CPR or double click table row.");
                        			return;
                        		}
                                try
                                {
                                	Employee emp = personCtrl.getEmployeeByCpr(tfEcpr.getText());
                                	personCtrl.updateEmployee(tfEcpr.getText(), emp.getPassword(), emp.getAccessType(), "Disabled");
                                    JOptionPane.showMessageDialog(null,"Employee has been successfuly deleted.");
                                    updateEmployeeTable();
                                    clearTextFields();
                                }
                                catch(Exception r)
                                {
                                        JOptionPane.showMessageDialog(null,"Error in deleting Employee.");
                                }
                        }
                });
                btnEdelete.setBounds(210, 459, 90, 31);
                empPanel.add(btnEdelete);
                btnEdelete.setFont(new Font("Times New Roman", Font.BOLD, 17));
                
                JLabel lblAccessLevel = new JLabel("Access Level :");
                lblAccessLevel.setHorizontalAlignment(SwingConstants.RIGHT);
                lblAccessLevel.setFont(new Font("Times New Roman", Font.PLAIN, 15));
                lblAccessLevel.setBounds(22, 346, 100, 31);
                empPanel.add(lblAccessLevel);
                
                tfEpassword = new JPasswordField();
                tfEpassword.setBounds(130, 390, 170, 25);
                empPanel.add(tfEpassword);
                
                tfEconfirmPassword = new JPasswordField();
                tfEconfirmPassword.setBounds(130, 421, 170, 25);
                empPanel.add(tfEconfirmPassword);
                
                lblListOfEmployees = new JLabel("LIST OF EMPLOYEES");
                lblListOfEmployees.setHorizontalAlignment(SwingConstants.CENTER);
                lblListOfEmployees.setFont(new Font("Times New Roman", Font.BOLD, 15));
                lblListOfEmployees.setBounds(10, 8, 692, 31);
                contentPane.add(lblListOfEmployees);
                
                lblManageEmployees = new JLabel("MANAGE EMPLOYEES");
                lblManageEmployees.setHorizontalAlignment(SwingConstants.CENTER);
                lblManageEmployees.setFont(new Font("Times New Roman", Font.BOLD, 15));
                lblManageEmployees.setBounds(712, 8, 312, 31);
                contentPane.add(lblManageEmployees);
                
                comboEmp = new JComboBox<String>();
                comboEmp.setSelectedIndex(-1);
                comboEmp.setBounds(10, 22, 170, 25);
                contentPane.add(comboEmp);
                
                DefaultComboBoxModel<String> empModel = new DefaultComboBoxModel<String>();
                empModel.addElement("Availiable");
                empModel.addElement("Unavailiable");
                comboEmp.setModel(empModel);
                comboEmp.setSelectedIndex(0);
                
                comboEmp.addActionListener(new ActionListener() {
        			public void actionPerformed(ActionEvent e) {
        				String availiability = (String)comboEmp.getSelectedItem();
        				System.out.println(availiability);
        				if(availiability.equals("Availiable"))
        				{
        					btnEupdate.setText("Update");
        					status = "Enabled";
        				}
        				if(availiability.equals("Unavailiable"))
        				{
        					status = "Disabled";
        					btnEupdate.setText("Rehire");
        				}
        				updateEmployeeTable();
        			}
        		});

        }
        
        public void setEmployeeFields(String cpr)
        {
        	 Employee emp = personCtrl.getEmployeeByCpr(cpr);
        	 tfEcpr.setText(emp.getCpr());
             tfEname.setText(emp.getName());
             tfEaddress.setText(emp.getAddress());
             tfEzipCode.setText(emp.getZipCode());
             tfEcity.setText(emp.getCity());
             tfEphone.setText(emp.getPhone());
             tfEgsm.setText(emp.getGsm());
             tfEemail.setText(emp.getEmail());
             //tfEpassword.setText(emp.getPassword());
             //tfEconfirmPassword.setText(emp.getPassword());
             if(emp.getAccessType().equals("Full Access"))
            	 comboAccess.setSelectedIndex(1);
             if(emp.getAccessType().equals("Limited Access"))
            	 comboAccess.setSelectedIndex(0);
        }
        
        public boolean ifPasswordEmpty()
        {
        	if(tfEpassword.getText().equals("") || tfEconfirmPassword.getText().equals(""))
        	{
        		JOptionPane.showMessageDialog(null, "You must specify a password and verify it.");
        		return true;
        	}
        	return false;
        }
        
        public boolean ifEmpty()
        {
                if(tfEcpr.getText().equals("") || tfEname.getText().equals("") || tfEaddress.getText().equals("") || tfEzipCode.getText().equals("") ||
                  tfEcity.getText().equals("") || tfEphone.getText().equals("") || tfEgsm.getText().equals("") || tfEemail.getText().equals(""))
                {
                        JOptionPane.showMessageDialog(null,"Some of the fields are empty.");
                        return true;
                }
                if(comboAccess.getSelectedIndex() == -1)
                {
                        JOptionPane.showMessageDialog(null,"Access type is not selected.");
                        return true;
                }
                
                return false;
        }
        
        public boolean ifPasswordsDontMatch()
        {
                if(!tfEpassword.getText().equals(tfEconfirmPassword.getText()))
                {
                        tfEpassword.setBackground(Color.MAGENTA);
                        tfEconfirmPassword.setBackground(Color.MAGENTA);
                        JOptionPane.showMessageDialog(null,"Passwords do not match.");
                        return true;
                }
                else
                return false;
        }
        
        public void setAccessType(String _accessType)
        {
        	
                if(_accessType.equals("Full Access"))
                {
                		accessType = true;
                		
                        //btnEadd.setEnabled(true);
                        //btnEupdate.setEnabled(true);
                        //btnEdelete.setEnabled(true);
                        
                        empPanel.setVisible(true);
                        lblManageEmployees.setVisible(true);
                        scrollPane.setBounds(10, 50, 692, 502);
                        lblListOfEmployees.setBounds(10, 8, 692, 31);
                        
                        if(empTable.getColumnCount() < 8)
                        {
                        	empTable.addColumn(cprColumn);
                        	empTable.addColumn(accessColumn);
                        	empTable.addColumn(passwordColumn);
                        }
                        
                }
                if(_accessType.equals("Limited Access"))
                {
                		accessType = false;
                		
                        //btnEadd.setEnabled(false);
                        //btnEupdate.setEnabled(false);
                        //btnEdelete.setEnabled(false);
                        
                        empPanel.setVisible(false);
                        lblManageEmployees.setVisible(false);
                        scrollPane.setBounds(10, 50, 1015, 502);
                        lblListOfEmployees.setBounds(180, 8, 692, 31);
                        
                        if(empTable.getColumnCount() > 7)
                        {
                        	cprColumn = empTable.getColumn("CPR");
                            accessColumn = empTable.getColumn("Access");
                            passwordColumn = empTable.getColumn("Password");
                            
                        	empTable.removeColumn(empTable.getColumn("CPR"));
                        	empTable.removeColumn(empTable.getColumn("Access"));
                        	empTable.removeColumn(empTable.getColumn("Password"));
                        }
                }
        }
        
        public boolean ifPersonExists()
        {
        	if(personCtrl.getPersonByCpr(tfEcpr.getText()) != null)
        		return true;
        	return false;
        }
        
        public boolean ifEmployeeExists()
        {
        	if(personCtrl.getEmployeeByCpr(tfEcpr.getText()) != null)
        		return true;
        	return false;
        }
        
        public void clearTextFields()
        {
                tfEcpr.setText("");
                tfEname.setText("");
                tfEaddress.setText("");
                tfEzipCode.setText("");
                tfEcity.setText("");
                tfEphone.setText("");
                tfEgsm.setText("");
                tfEemail.setText("");
                tfEpassword.setText("");
                tfEconfirmPassword.setText("");
                comboAccess.setSelectedIndex(-1);
                tfEpassword.setBackground(Color.WHITE);
                tfEconfirmPassword.setBackground(Color.WHITE);
        }
        
        public void updateEmployeeTable()
        {
        empT.setEmp(personCtrl.getAllEmployeesByStatus(status));
        empTable.setModel(empT);
        empTable.setAutoCreateRowSorter(true);
        }
}